package com.xiaoqi.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaoqi.reggie.common.CustomException;
import com.xiaoqi.reggie.dto.SetmealDto;
import com.xiaoqi.reggie.entity.Setmeal;
import com.xiaoqi.reggie.entity.SetmealDish;
import com.xiaoqi.reggie.service.SetmealDishService;
import com.xiaoqi.reggie.service.SetmealService;
import com.xiaoqi.reggie.mapper.SetmealMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
* @author xiaoqi
* @description 针对表【setmeal(套餐)】的数据库操作Service实现
* @createDate 2022-09-20 16:15:05
*/
@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal>
implements SetmealService{
    @Autowired
    SetmealDishService setmealDishService;

    @Override
    public void saveWithDish(SetmealDto setmealDto) {
        this.save(setmealDto);
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        Long id = setmealDto.getId();
        for (SetmealDish setmealDish:setmealDishes){
            setmealDish.setSetmealId(String.valueOf(id));
        }
        setmealDishService.saveBatch(setmealDishes);
    }

    @Override
    public void removeWithDish(List<Long> ids) {
        //查询套餐状态，确定是否可用删除
        LambdaQueryWrapper<Setmeal>queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(Setmeal::getStatus,1);
        queryWrapper.in(Setmeal::getId,ids);
        int count = this.count(queryWrapper);
        if (count>0){
            throw new CustomException("套餐正在售卖中，不能删除");
        }
        //在setmeal表中根据id删除
        this.removeByIds(ids);
        //在setmealDish表中也删除相关数据
        LambdaQueryWrapper<SetmealDish> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.in(SetmealDish::getSetmealId,ids);
        setmealDishService.remove(lambdaQueryWrapper);
    }

    @Override
    public void updateWithDish(SetmealDto setmealDto) {
        //先修改setmeal表中的内容
        this.updateById(setmealDto);
        //先清空setmealdish表中SetmealId为该菜品的信息
        LambdaQueryWrapper<SetmealDish>queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(SetmealDish::getSetmealId,setmealDto.getId());
        setmealDishService.remove(queryWrapper);
        //将setmealDto中的SetmealDishes添加进setmealdish表中，在此之前先给这些元素的SetmealId赋值
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        for (SetmealDish setmealDish:setmealDishes){
            setmealDish.setSetmealId(String.valueOf(setmealDto.getId()));
        }
        //将这些数据存入表中
        setmealDishService.saveBatch(setmealDishes);
    }

}
